package solution22;

import java.util.ArrayList;
import java.util.List;

/**
 * 22. Generate Parentheses
 */
public class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> res = new ArrayList<String>();
        helper(n, n, "", res);
        return res;
    }

    // 递归，((())) ,(()()) ,(())() ,()(()) ,()()()
    private void helper(int left, int right, String out, List<String> res) {
//        System.out.println(out+ " "+left + " "+right);// 规律测试
        if (left < 0 || right < 0 || left > right) return;
        if (left == 0 && right == 0) {
            res.add(out);
            return;
        }
        helper(left - 1, right, out + "(", res);
        helper(left, right - 1, out + ")", res);
    }
}
